import React, { useState,useEffect, useTransition,useRef  } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select, Tabs,Tooltip,List,Table,Tree,Pagination } from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined,SearchOutlined,FileOutlined  } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { listRisksubstance,getRisksubstance,delRisksubstance,addRisksubstance,updateRisksubstance} from "@/api/modules/jnj/risksubstance";
import { listSarm} from "@/api/modules/jnj/rm";
import { listSubstance,editSubstance,addSubstance,delSubstance} from "@/api/modules/risksub";
import { listFunction,getFunction,delFunction,addFunction,updateFunction} from "@/api/modules/jnj/safetyFunction";
import { listCategory,getCategory,delCategory,addCategory,updateCategory,batchLink} from "@/api/modules/jnj/safetyCategory";
import { ProFormColumnsType } from '@ant-design/pro-components'
import FullscreenLoading from '@/components/FullscreenLoading';
import { getInfo } from "@/api/login/ssoLogin";

const {TextArea} = Input;
const { Option } = Select;
const { TabPane } = Tabs; 

const rmrisksub = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [isModalVisible2, setIsModalVisible2] = useState(false); 
  const [Title2, setTitle2] = useState("")  
  const [form2] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [isView, SetisView] = useState(false)
  const [isView2, SetisView2] = useState(false)
  const [riskdistances,setRiskdistances] = useState([]); 
  const [onReloadNum, setReloadNum] = useState(0); 
  const [onReloadNum2, setReloadNum2] = useState(0); 
  const [peoplelist,setPeople] = useState([])
  const [tab1Data,setTab1Data] = useState([])
  const [riskTable,setRisktable] = useState([])
  const [isTreeModalVisible,setIsTreeModalVisible] = useState(false)
  const [newtreeData,setTreedata] = useState([])
  const [checkedKeys, setCheckedKeys] = useState([]); // 用于保存勾选的节点key 
  const [checkIds, setcheckIds] = useState([]); // 用于保存勾选的节点keyid
  const [selectId, setSelectId] = useState(null); // 用于保存下拉框
  const [loading, setLoading] = useState(false); 
  const [total, setTotal] = useState(0); // 总条目数  
  const [currentPage, setCurrentPage] = useState(1); // 当前页码  
  const [pageSize, setPageSize] = useState(10); // 每页显示的条目数  
   // 搜索框的状态  
 const [name, setIngredient] = useState(''); 
 const [description, setDescription] = useState(''); 
 const [viewStatus, setViewStatus] = useState(false); // 加载状态 

 useEffect(()=>{
  getInfo().then(res=>{
    console.log(res,'res')
    const data = res.data
    data.roles.forEach((item)=>{
      if(item == "Formulator"){
        setViewStatus(true)
      }
    })
  }) 
  const query={pageNum:1,pageSize:10}
  getData2(query)
  getRiskList()
 },[])

  const formColumns:ProFormColumnsType[] = [ {
    title: t('risksubstance.risksubstance'),
    dataIndex: 'search',
    valueType: 'text', 
  }
    
  ]

  const columns: any = [
    {
      title: t('inci.riskEn'),
      dataIndex: 'riskEn',
      key: 'riskEn',
      width: 150,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (riskEn) => (
        <Tooltip placement="topLeft" title={riskEn}>
          {riskEn}
        </Tooltip>
      ),
    },
    {
      title: t('inci.riskCn'),
      dataIndex: 'riskCn',
      key: 'riskCn',
      ellipsis: {
        showTitle: false,
      },
      render: (riskCn) => (
        <Tooltip placement="topLeft" title={riskCn}>
          {riskCn}
        </Tooltip>
      ),
    },
    {
      title: t('risksubstance.type'),
      dataIndex: 'type',
      key: 'type',
      ellipsis: {
        showTitle: false,
      },
      render: (type) => (
        <Tooltip placement="topLeft" title={type}>
          {type}
        </Tooltip>
      ),
    },
    {
      title: t('risksubstance.maximum'),
      dataIndex: 'maximum',
      key: 'maximum',
      ellipsis: {
        showTitle: false,
      },
      render: (maximum) => (
        <Tooltip placement="topLeft" title={maximum}>
          {maximum}
        </Tooltip>
      ),
    },
    {
      title: t('risksubstance.testMethod'),
      dataIndex: 'testMethod',
      key: 'testMethod',
      ellipsis: {
        showTitle: false,
      },
      render: (testMethod) => (
        <Tooltip placement="topLeft" title={testMethod}>
          {testMethod}
        </Tooltip>
      ),
    },
    {
      title: t('risksubstance.legalSource'),
      dataIndex: 'legalSource',
      key: 'legalSource',
      ellipsis: {
        showTitle: false,
      },
      render: (legalSource) => (
        <Tooltip placement="topLeft" title={legalSource}>
          {legalSource}
        </Tooltip>
      ),
    },
    {
      title: t('risksubstance.comment'),
      dataIndex: 'comment',
      key: 'comment',
      ellipsis: {
        showTitle: false,
      },
      render: (comment) => (
        <Tooltip placement="topLeft" title={comment}>
          {comment}
        </Tooltip>
      ),
    },
    {
      title: t('risksubstance.remarkCn'),
      dataIndex: 'remarkCn',
      key: 'remarkCn',
      ellipsis: {
        showTitle: false,
      },
      render: (remarkCn) => (
        <Tooltip placement="topLeft" title={remarkCn}>
          {remarkCn}
        </Tooltip>
      ),
    },
    {
      title: t('risksubstance.diagnosticCn'),
      dataIndex: 'diagnosticCn',
      key: 'diagnosticCn',
      ellipsis: {
        showTitle: false,
      },
      render: (diagnosticCn) => (
        <Tooltip placement="topLeft" title={diagnosticCn}>
          {diagnosticCn}
        </Tooltip>
      ),
    },
    {
      title: t('risksubstance.diagnosticEn'),
      dataIndex: 'diagnosticEn',
      key: 'diagnosticEn',
      ellipsis: {
        showTitle: false,
      },
      render: (diagnosticEn) => (
        <Tooltip placement="topLeft" title={diagnosticEn}>
          {diagnosticEn}
        </Tooltip>
      ),
    },
    {
      title: t('risksubstance.dataReference'),
      dataIndex: 'dateReference',
      key: 'dateReference',
      ellipsis: {
        showTitle: false,
      },
      render: (dateReference) => (
        <Tooltip placement="topLeft" title={dateReference}>
          {dateReference}
        </Tooltip>
      ),
    },
    {
      title: t('risksubstance.filename'),
      dataIndex: 'filename',
      key: 'filename',
      ellipsis: {
        showTitle: false,
      },
      render: (filename) => (
        <Tooltip placement="topLeft" title={filename}>
          {filename}
        </Tooltip>
      ),
    },  
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
         <Button type="link" onClick={() => handleView(record)}>  
          {t('view')}  
          </Button>  
          {viewStatus ? null : (
            <>
                 <Button type="link" onClick={() => handleEdit(record)}>  
                {t('edit')}  
                </Button>  
                <Button type="link" danger onClick={() => handleDelete(record.id)}>  
                {t('delete')}   
                </Button>  
            </>
          )}
       
   
        </>  
      ),  
    },  
  ];


  const getData = async (formData) => {
    const { success, data} = await listSubstance({...formData,orderByColumn:'id',isAsc:'desc', order: 0})
    if(!success) return false
    let list = data.data.page

    return {
      data: list,
      total: data.data.total
    }
  } 

  const handleAdd = () =>{
    SetisView(false)
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    setLoading(true)
    const values = form.getFieldsValue(); 
    if(values.dateReference =="" || values.dateReference == null || values.dateReference == undefined){
      values.dateReference=""
    }else{
      values.dateReference=values.dateReference.join(',')
    }
    if(Title=='修改/Edit'){
      editSubstance(values).then(response => {
        message.success("success")
        setIsModalVisible(false);
        setReloadNum(onReloadNum+1)
        setLoading(false)
       });  
      }else{
        addSubstance(values).then(response => {
          message.success("success")
          setIsModalVisible(false);
          setReloadNum(onReloadNum+1)
          setLoading(false)
         });
      }

    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleView = (record) =>{
   SetisView(true)
   setTitle("查看/View")
   console.log(record,'record')
   if (record.dateReference === null || record.dateReference === undefined || typeof record.dateReference !== 'string') {  
    // 如果 reference 是 null、undefined 或不是字符串类型（可能是数组或其他类型），我们将其设置为空字符串或空数组  
    record.dateReference = typeof record.dateReference === 'object' && Array.isArray(record.dateReference) ? record.dateReference : ""; // 保持数组类型或设置为空字符串  
  } else {  
    // 如果 reference 是一个非空字符串且不是数组，我们将其分割为数组  
    record.dateReference = record.dateReference.split(',');  
  }
  
   form.setFieldsValue({ ...record });  
   setIsModalVisible(true);  
  }

  const handleEdit = (record) =>{
    SetisView(false)
    setTitle("修改/Edit")
      // 假设 record 是一个对象，并且您想要处理它的 reference 属性  
      if (record.dateReference === null || record.dateReference === undefined || typeof record.dateReference !== 'string') {  
        // 如果 reference 是 null、undefined 或不是字符串类型（可能是数组或其他类型），我们将其设置为空字符串或空数组  
        record.dateReference = typeof record.dateReference === 'object' && Array.isArray(record.dateReference) ? record.dateReference : ""; // 保持数组类型或设置为空字符串  
      } else {  
        // 如果 reference 是一个非空字符串且不是数组，我们将其分割为数组  
        record.dateReference = record.dateReference.split(',');  
      }
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        setLoading(true)
        delSubstance(inciIds).then(res=>{
            message.success("Success")
            setReloadNum(onReloadNum+1)
            setLoading(false)
        }) 
      },  
    }); 
  }
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  //select查询

  const [searchResult, setSearchResult] = useState([]);  
  const [visible, setVisible] = useState(false);  
  const [selectedResult, setSelectedResult] = useState(null);  
  
  const handleSearch = (values) => {  
    // 假设这里有一个异步的搜索函数，它返回搜索结果  
    const fakeSearch = async () => {  
      const inci = form2.getFieldsValue()
      const data={
        pageNum: 1,
        pageSize: 50,
        searchValue:inci.inciStr,
    }
    listSarm(data).then(res=>{
        let incis=res.data.rows
        incis.map(item=>{
          item.name='Code:'+item.rmNumber +',Name:' +item.rmName
        })
        setSearchResult(incis);
        setVisible(true);  
    })
    };  
    fakeSearch()
  };  
  
  const handleSelectResult = (result) => {  
    form2.setFieldsValue({ inciStr: result.name }); // 回填表单  
    form2.setFieldsValue({ safetyRmId: result.safetyRmId }); // 回填表单 
    form2.setFieldsValue({rmNumber:result.rmNumber})
    form2.setFieldsValue({rmName:result.rmName})
    setSelectedResult(result);  
    setVisible(false); // 关闭弹窗  
  };  
  
  const modalFooter = [  
    <Button key="back" onClick={() => setVisible(false)}>  
      取消  
    </Button>,  
    <Button key="submit" type="primary" onClick={() => handleSelectResult(selectedResult)}>  
      选择  
    </Button>,  
  ];  

  //风险物质列表

  
  const formColumns2:ProFormColumnsType[] = [
    {
      title: t('function.name'),
      dataIndex: 'name',
      valueType: 'text', 
    },{
      title: t('function.decription'),
      dataIndex: 'decription',
      valueType: 'text', 
    }
  ]

  const columns2: any = [
    {
      title: t('rmrisk.rmNumber'),
      dataIndex: 'rmNumber',
      key: 'rmNumber',
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (rmNumber) => (
        <Tooltip placement="topLeft" title={rmNumber}>
          {rmNumber}
        </Tooltip>
      ),
    },
    {
      title: t('rmrisk.rmName'),
      dataIndex: 'rmName',
      key: 'rmName',
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (decription) => (
        <Tooltip placement="topLeft" title={decription}>
          {decription}
        </Tooltip>
      ),
    },
    {
      title: t('rmrisk.risksubstance'),
      dataIndex: 'risksubstance',
      key: 'risksubstance',
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (risksubstance) => (
        <Tooltip placement="topLeft" title={risksubstance}>
          {risksubstance}
        </Tooltip>
      ),
    },
  ];

  const getRiskList = () =>{
    const query ={
      page: 1,
      limit: 9999,
      search:null,
      orderby: "",
      order: 0,
      total: 0,
      offset: 0
    } 
    listSubstance(query).then(res=>{
      setRisktable(res.data.data.page)
    })
      
  }

  const getData2 = async (formData) => {
    const { success, data} = await listRisksubstance({...formData, order: 0})
    if(!success) return false
    console.log(data)
    let list2 = data.rows
    list2.map(i=>{
      i.key=i.rmNumber
    })
    setTab1Data(list2)
    setTotal(data.total)
    return {
      data: list2,
      total: data.total
    }
  } 


  const handleAdd2 = () =>{
    SetisView2(false)
    form2.resetFields()
    setTitle2("新增/New")
    showModal2()
  }

  const showModal2 = () => {  
    setIsModalVisible2(true);  
  };  

  
  const handleOk2 = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form2.getFieldsValue(); 
    if(values.reference=="" || values.reference==null || values.reference==undefined){
      values.reference=""
    }else{
      values.reference=values.reference.join(',')
    }
    if(Title2=='新增/New'){
        //新增
        values.id =null
        addRisksubstance(values).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
             // 假设添加成功，关闭弹窗  
            setIsModalVisible2(false); 
            fetchData2(currentPage,pageSize,'',''); // 获取新页的数据  
        }).catch(()=>{
           
        })
    }else{
        //修改
        updateRisksubstance(values).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
             // 假设添加成功，关闭弹窗  
            setIsModalVisible2(false);  
            fetchData2(currentPage,pageSize,'',''); // 获取新页的数据  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleView2 = (record) =>{
   SetisView2(true)
   setTitle2("查看/View")
   console.log(record,'record')
     // 假设 record 是一个对象，并且您想要处理它的 reference 属性  
  if (record.reference === null || record.reference === undefined || typeof record.reference !== 'string') {  
    // 如果 reference 是 null、undefined 或不是字符串类型（可能是数组或其他类型），我们将其设置为空字符串或空数组  
    record.reference = typeof record.reference === 'object' && Array.isArray(record.reference) ? record.reference : ""; // 保持数组类型或设置为空字符串  
  } else {  
    // 如果 reference 是一个非空字符串且不是数组，我们将其分割为数组  
    record.reference = record.reference.split(',');  
  }
   form2.setFieldsValue({ ...record });  
   setIsModalVisible2(true);  
  }

  const handleEdit2 = (record) =>{
    SetisView2(false)
    setTitle2("修改/Edit")
    console.log(record,'record')
  // 假设 record 是一个对象，并且您想要处理它的 reference 属性  
  if (record.reference === null || record.reference === undefined || typeof record.reference !== 'string') {  
    // 如果 reference 是 null、undefined 或不是字符串类型（可能是数组或其他类型），我们将其设置为空字符串或空数组  
    record.reference = typeof record.reference === 'object' && Array.isArray(record.reference) ? record.reference : ""; // 保持数组类型或设置为空字符串  
  } else {  
    // 如果 reference 是一个非空字符串且不是数组，我们将其分割为数组  
    record.reference = record.reference.split(',');  
  }
    form2.setFieldsValue({ ...record });  
    setIsModalVisible2(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete2 = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        delRisksubstance(key).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
            fetchData2(currentPage,pageSize,'',''); // 获取新页的数据  
        }) 
      },  
    }); 
  }
  
  const handleCancel2 = () => {  
    setIsModalVisible2(false);  
  };  

  const expandedColumns : any =[
    {  
      title: t('rmrisk.riskCn'),  
      dataIndex: ['productRisksubstance','riskCn'],  
      key: 'productRisksubstance.riskCn',  
      fixed:'left',
      width:100,
      ellipsis: {
        showTitle: false,
      },
      render: (riskCn) => (
        <Tooltip placement="topLeft" title={riskCn}>
          {riskCn}
        </Tooltip>
      ),
    },  
    {  
      title: t('rmrisk.riskEn'),  
      dataIndex: ['productRisksubstance','riskEn'], 
      key: 'productRisksubstance.riskEn',  
      fixed:'left',
      width:100,
      ellipsis: {
        showTitle: false,
      },
      render: (riskEn) => (
        <Tooltip placement="topLeft" title={riskEn}>
          {riskEn}
        </Tooltip>
      ),
    },    
    {  
      title: t('rmrisk.contain'),  
      dataIndex: 'contain',  
      key: 'contain',  
      width:100,
      ellipsis: {
        showTitle: false,
      },
      render: (contain) => (
        <Tooltip placement="topLeft" title={contain}>
          {contain}
        </Tooltip>
      ),
    },  
    {  
      title: t('rmrisk.diagnosticCn'),  
      dataIndex: ['productRisksubstance','diagnosticCn'],  
      key: 'productRisksubstance.diagnosticCn', 
      width:140,
      ellipsis: {
        showTitle: false,
      },
      render: (diagnosticCn) => (
        <Tooltip placement="topLeft" title={diagnosticCn}>
          {diagnosticCn}
        </Tooltip>
      ), 
    },  
    {  
      title: t('rmrisk.concentration'),  
      dataIndex: 'concentration',  
      key: 'concentration',  
      width:140,
      ellipsis: {
        showTitle: false,
      },
      render: (concentration) => (
        <Tooltip placement="topLeft" title={concentration}>
          {concentration}
        </Tooltip>
      ), 
    },  
    {  
      title: t('rmrisk.symbol'),  
      dataIndex: 'symbol',  
      key: 'symbol',  
      width:140,
      ellipsis: {
        showTitle: false,
      },
      render: (symbol) => (
        <Tooltip placement="topLeft" title={symbol}>
          {symbol}
        </Tooltip>
      ), 
    },  
    {  
      title: t('rmrisk.unit'),  
      dataIndex: 'unit',  
      key: 'unit',  
      width:140,
      ellipsis: {
        showTitle: false,
      },
      render: (unit) => (
        <Tooltip placement="topLeft" title={unit}>
          {unit}
        </Tooltip>
      ), 
    },  
    {  
      title: t('rmrisk.dailyAmountG'),  
      dataIndex: 'dailyAmountG',  
      key: 'dailyAmountG',  
      width:120,
      ellipsis: {
        showTitle: false,
      },
      render: (dailyAmountG) => (
        <Tooltip placement="topLeft" title={dailyAmountG}>
          {dailyAmountG}
        </Tooltip>
      ), 
    },  
    {  
      title: t('rmrisk.dailyAmountMg'),  
      dataIndex: 'dailyAmountMg',  
      key: 'dailyAmountMg', 
      width:120,
      ellipsis: {
        showTitle: false,
      },
      render: (dailyAmountMg) => (
        <Tooltip placement="topLeft" title={dailyAmountMg}>
          {dailyAmountMg}
        </Tooltip>
      ),  
    },  
    {  
      title: t('rmrisk.retentionFactor'),  
      dataIndex: 'retentionFactor',  
      key: 'retentionFactor', 
      width:120, 
      ellipsis: {
        showTitle: false,
      },
      render: (retentionFactor) => (
        <Tooltip placement="topLeft" title={retentionFactor}>
          {retentionFactor}
        </Tooltip>
      ),  
    },  
    {  
      title: t('rmrisk.comment'),  
      dataIndex: 'comment',  
      key: 'comment',  
      width:120,
      ellipsis: {
        showTitle: false,
      },
      render: (comment) => (
        <Tooltip placement="topLeft" title={comment}>
          {comment}
        </Tooltip>
      ), 
    },  
    {  
      title: t('rmrisk.reference'),  
      dataIndex: 'reference',  
      key: 'reference',
      width:120, 
      ellipsis: {
        showTitle: false,
      },
      render: (reference) => (
        <Tooltip placement="topLeft" title={reference}>
          {reference}
        </Tooltip>
      ),  
    },  
    {  
      title: t('rmrisk.process'),  
      dataIndex: 'process',  
      key: 'process',
      width:120,  
      ellipsis: {
        showTitle: false,
      },
      render: (process) => (
        <Tooltip placement="topLeft" title={process}>
          {process}
        </Tooltip>
      ),  
    },  
    {  
      title: t('rmrisk.wording'),  
      dataIndex: 'wording',  
      key: 'wording', 
      width:120,
      ellipsis: {
        showTitle: false,
      },
      render: (wording) => (
        <Tooltip placement="topLeft" title={wording}>
          {wording}
        </Tooltip>
      ),   
    },  
    {  
      title: t('action'),  
      key: 'action',
      width:170,
      fixed:'right',
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView2(record)}>  
           {t('view')}  
          </Button> 
          {viewStatus ? null : (
            <>
                 <Button type="link" onClick={() => handleEdit2(record)}>  
                  {t('edit')}  
                  </Button>  
                  <Button type="link" danger onClick={() => handleDelete2(record.id)}>  
                  {t('delete')}   
                  </Button>  
            </>
          )}
        </>  
      ),  
    }, 
  ]

  const expandedRowRender = (record) => {  
    // 如果record有subData属性，则渲染子表格  
    if (record.rmRisksubstanceList && record.rmRisksubstanceList.length > 0) {  
      // 使用subData作为子表格的数据源  
      return <Table columns={expandedColumns} dataSource={record.rmRisksubstanceList} pagination={false}  scroll={{ x: '1000px' }}  />;
    }  
    return null; // 如果没有子数据，则不渲染内容  
  };  

 // 重置函数  
 const handleReset = () => {  
      setIngredient(''); // 清空搜索框  
      // 可能还需要将 currentPage 重置为 1，取决于你的需求  
      // setCurrentPage(1);  
      setDescription('');
      fetchData2(currentPage,pageSize,'',''); // 获取新页的数据  
    };  
  
  // 搜索函数  
  const handleSearch2 = () => {  
    fetchData2(1,10,name,description)
  };  
  const fetchData2 = async (currentPage,pageSize,name,description) => {
    const param = {pageNum:currentPage,pageSize:pageSize,rmNumber:name,rmName:description,}
    const { success, data} = await listRisksubstance(param)
    if(!success) return false
    console.log(data)
    let list2 = data.rows
    list2.map(i=>{
      i.key=i.rmNumber
    })
    setTab1Data(list2)
    setTotal(data.total) 
    return {
      data: list2,
      total: data.total
    }
  } 
  
  const onCheck = (checkedKeysValue) => { 
    let checkId = []
    if(checkedKeysValue.length>0){
      checkedKeysValue.map(i=>{
        newtreeData.map(k=>{
          k.children.map(o=>{
            if(i==o.key){
              checkId.push(o.id)
            }
          })
        })
      })
      setcheckIds(checkId); // 更新状态以保存勾选的节点key  
      setCheckedKeys(checkedKeysValue)
    }else{
      setcheckIds(checkedKeysValue);
      setCheckedKeys(checkedKeysValue)
    }
   
  };  
  const handleSelectChange = (value) => {  
    setSelectId(value);  
  };  

    // 处理页码变化  
    const handlePageChange = (page,pageSize) => {
      console.log(page,'page') 
      setCurrentPage(page)
      setPageSize(pageSize)
      fetchData2(page,pageSize,'',''); // 获取新页的数据  
    };  

  const renderOperator = <>
    <Button disabled={viewStatus} type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
  </>
    // 自定义是否可展开的函数  
    const rowExpandable = (record) => record.name !== 'Not Expandable';  
  return (
    <div> 
      <Card>
      <Tabs type="card" defaultActiveKey="原料功能"> 
      <TabPane tab={t('risksubstance.risksubstanceAc')} key="风险物质关联">
        <Card className="box-card" style={{ marginBottom: 24, minWidth: '700px' }}>  
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>  
          <div style={{ marginRight: '20px' }}>  
            <div style={{ fontWeight: 'bold' }}>{t('rmrisk.rmNumber')}</div>  
            <Input style={{ width: '240px' }} value={name} onChange={(e) => setIngredient(e.target.value)} />  
          </div>  
          <div>  
            <div style={{ fontWeight: 'bold', marginRight: '10px' }}>{t('rmrisk.rmName')}</div>  
            <Input style={{ width: '240px' }} value={description} onChange={(e) => setDescription(e.target.value)} />  
          </div>  
          <div style={{ display: 'flex', alignItems: 'center', marginLeft: 'auto' }}>  
            <Button onClick={handleReset} size='small' style={{ marginRight: '8px' }}>{t('cancel')}</Button>  
            <Button type="primary" size='small' onClick={handleSearch2}>{t('search')}</Button>  
          </div>  
        </div>
      </Card> 
      <Button size='small' disabled={viewStatus} style={{marginBottom:'2%'}} type="primary" onClick={handleAdd2}>  
          {t('add')}  
        </Button> 
      
        <Table  
          dataSource={tab1Data}  
          columns={columns2} 
          expandable={{  
            expandedRowRender,  
            rowExpandable,  
          }}  
          pagination={false}
        />  
       <Pagination  
          current={currentPage}  
          pageSize={pageSize}  
          total={total}  
          size='small'
          onChange={handlePageChange}  
        />    
        </TabPane>  
        <TabPane tab={t('risksubstance.risksubstanceList')} key="风险物质列表">  
          <MemoTable 
            name='rmrisksub'
            formColumns={formColumns}
            columns={columns as any}
            rowKey='id'
            operator={renderOperator}
            getData={getData}
            refreshKey={onReloadNum}
          /> 
        </TabPane>  
       
      </Tabs> 
      </Card>
       
      <FullscreenLoading showLoading={loading} loadingTip="Loading..."/> 
    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}   
            <Form.Item  
              name="riskEn"  
              label={t('inci.riskEn')} 
              rules={[{ required: true, message: '请输入英文名称！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="riskCn"  
              label={t('inci.riskCn')}  
              rules={[{ required: true, message: '请输入中文名称！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="type"  
              label={t('risksubstance.type')}  
            >  
               <Input disabled={isView}/>   
            </Form.Item> 
            <Form.Item  
              name="maximum"  
              label={t('risksubstance.maximum')}  
            >  
               <Input disabled={isView}/>   
            </Form.Item> 
            <Form.Item  
              name="testMethod"  
              label={t('risksubstance.testMethod')}  
            >  
               <Input disabled={isView}/>   
            </Form.Item> 
            <Form.Item  
              name="legalSource"  
              label={t('risksubstance.legalSource')}  
            >  
               <Input disabled={isView}/>   
            </Form.Item> 
            <Form.Item  
              name="comment"  
              label={t('risksubstance.comment')}  
            >  
               <Input.TextArea disabled={isView}/>   
            </Form.Item> 
            <Form.Item  
              name="diagnosticEn"  
              label={t('risksubstance.diagnosticEn')}  
            >  
               <Input.TextArea disabled={isView}/>   
            </Form.Item> 
            <Form.Item  
              name="diagnosticCn"  
              label={t('risksubstance.diagnosticCn')}  
            >  
               <Input.TextArea disabled={isView}/>   
            </Form.Item> 
            <Form.Item  
              name="remarkCn"  
              label={t('risksubstance.remarkCn')}  
            >  
               <Input.TextArea disabled={isView}/>   
            </Form.Item> 
            <Form.Item  
              name="dateReference"  
              label={t('risksubstance.dataReference')}  
            >  
               <Select mode="tags" disabled={isView}>
                  <Option value="2015安全技术规范">2015安全技术规范</Option>
                </Select>   
            </Form.Item> 
            <Form.Item  
              name="filename"  
              label={t('risksubstance.filename')}  
            >  
               <Input disabled={isView}/>   
            </Form.Item>
          </Form>  
        </Modal>  
        <Modal  
          title={Title2}
          visible={isModalVisible2}  
          onOk={handleOk2}  
          onCancel={handleCancel2}  
        >  
          <Form form={form2} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            <Form.Item  
                name="safetyRmId"  
                label="safetyRmId" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item name="inciStr" label={t('rmrisk.searchRm')}>  
            <Input />  
          </Form.Item>  
          <Form.Item>  
            <Button type="primary" htmlType="submit" onClick={handleSearch}>  
              点击搜索  
            </Button>  
          </Form.Item>
          <Modal  
        title="Result"  
        visible={visible}  
        onCancel={() => setVisible(false)}  
        footer={modalFooter}  
      >  
        <List  
          itemLayout="horizontal"  
          dataSource={searchResult}  
          renderItem={(item) => (  
            <List.Item  
              actions={[  
                <Button type="link" onClick={() => handleSelectResult(item)}>  
                  选择  
                </Button>,  
              ]}  
            >  
              <List.Item.Meta  
                title={<span>{item.name}</span>}  
              />  
            </List.Item>  
          )}  
        />  
      </Modal>    
            <Form.Item  
              name="productRisksubstanceId"  
              label={t('rmrisk.productRisksubstanceId')}
              rules={[{ required: true, message: 'Please Select' }]} 
            >  
              <Select disabled={isView2}>
              {riskTable.map((item) => (  
                <Select.Option key={item.id} value={item.id}>  
                   {'riskCn:'+item.riskCn+',riskEn:'+item.riskEn}
                </Select.Option>  
              ))} 
              </Select>  
            </Form.Item>  
            <Form.Item  
              name="rmNumber"  
              label={t('rmrisk.rmNumber')}
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled/>  
            </Form.Item>  
            <Form.Item  
              name="rmName"  
              label={t('rmrisk.rmName')}
          
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled/>  
            </Form.Item> 
            <Form.Item  
              name="contain"  
              label={t('rmrisk.contain')}
            >  
              <Select disabled={isView2}>
                <Option value="YES">YES</Option>  
                <Option value="NO">NO</Option>  
              </Select>  
            </Form.Item> 
            <Form.Item  
              name="concentration"  
              label={t('rmrisk.concentration')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item> 
            <Form.Item  
              name="symbol"  
              label={t('rmrisk.symbol')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item> 
            <Form.Item  
              name="unit"  
              label={t('rmrisk.unit')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item> 
            <Form.Item  
              name="dailyAmountG"  
              label={t('rmrisk.dailyAmountG')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item> 
            <Form.Item  
              name="dailyAmountMg"  
              label={t('rmrisk.dailyAmountMg')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item> 
            <Form.Item  
              name="retentionFactor"  
              label={t('rmrisk.retentionFactor')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item> 
            <Form.Item  
              name="reference"  
              label={t('rmrisk.reference')}
            >  
              <Select mode="tags" disabled={isView2}>
                  <Option value="2015安全技术规范">2015安全技术规范</Option>
               </Select>   
            </Form.Item> 
            <Form.Item  
              name="comment"  
              label={t('rmrisk.comment')}
            >  
              <Input.TextArea disabled={isView2}/>  
            </Form.Item> 
            <Form.Item  
              name="process"  
              label={t('rmrisk.process')}
            >  
              <Input.TextArea disabled={isView2}/>  
            </Form.Item>
            <Form.Item  
              name="wording"  
              label={t('rmrisk.wording')}
            >  
              <Input.TextArea disabled={isView2}/>  
            </Form.Item>  
          </Form>  
        </Modal> 
    </div>
  )
}
export default rmrisksub
